package com.android.djlmapp.activity.kuandai;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.kaika.QianMingActivity;
import com.android.djlmapp.activity.kaika.ShiMingRengZhengActivity;
import com.android.djlmapp.activity.kaika.TiaoXingCodeScanerActivity;
import com.android.djlmapp.activity.kaika.web.LianTongXieYiListActivity;
import com.android.djlmapp.activity.kuandai.base.KuanDaiBaseActivity;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.dialog.MyUsualyDialog;
import com.android.djlmapp.holder.ZhwjViewHolder;
import com.android.djlmapp.model.eventbus.FaceRzInfo;
import com.android.djlmapp.model.kaika.SimNumInfo;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.other.TextUtil;
import com.android.djlmapp.tools.read.WriteCardUtils;
import com.android.readcard.activity.WriteCardActivity;
import com.android.readcard.bean.ReadIccidAndWriteCardInfo;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 智慧沃家
 */
@RuntimePermissions
public class ZhiHuiWoJiaActivity extends KuanDaiBaseActivity {

    @BindView(R.id.top_bac)
    ImageView topBac;
    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.top_notes)
    ImageView topNotes;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.tv_top_jump)
    TextView tvTopJump;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.kuandai_tv_address)
    TextView kuandaiTvAddress;
    @BindView(R.id.kuandai_buchong)
    EditText kuandaiBuchong;
    @BindView(R.id.ed_tv_zyhf)
    EditText kuandaiZyhf;
    @BindView(R.id.tv_xzhm)
    TextView tvXzhm;
    @BindView(R.id.kk_tv_xzhm)
    TextView kkTvXzhm;
    @BindView(R.id.zhwj_icon)
    ImageView zhwjIcon;
    @BindView(R.id.zhwj_add_phone)
    ImageView zhwjAddPhone;
    @BindView(R.id.zhwj_parent)
    LinearLayout zhwjParent;
    @BindView(R.id.tv_smrz)
    TextView tvSmrz;
    @BindView(R.id.kk_tv_smrz)
    TextView kkTvSmrz;
    @BindView(R.id.cl_shiming)
    ConstraintLayout clShiming;
    @BindView(R.id.tv_smname)
    TextView tvSmname;
    @BindView(R.id.kk_tv_name)
    TextView kkTvName;
    @BindView(R.id.kk_cl_name)
    ConstraintLayout kkClName;
    @BindView(R.id.tv_cardnum)
    TextView tvCardnum;
    @BindView(R.id.kk_tv_cardnum)
    TextView kkTvCardnum;
    @BindView(R.id.kk_cl_cardnum)
    ConstraintLayout kkClCardnum;
    @BindView(R.id.kk_iv_photo)
    ImageView kkIvPhoto;
    @BindView(R.id.cl_smrz_item)
    RelativeLayout clSmrzItem;
    @BindView(R.id.tv_lxhm)
    TextView tvLxhm;
    @BindView(R.id.ll_tv_lxhm)
    EditText llTvLxhm;
    @BindView(R.id.kk_qianming_photo)
    ImageView kkQianmingPhoto;
    @BindView(R.id.cb_xieyi)
    CheckBox cbXieyi;
    @BindView(R.id.dkd_scroll)
    ScrollView dkdScroll;
    @BindView(R.id.dkd_tv_submit)
    TextView dkdTvSubmit;

    private static final int SIMREQUEST_CODE = 110;
    private static final int PHONEREQUEST_CODE = 111;
    private static final int CODEREQUEST_CODE = 112;
    @BindView(R.id.zhwj_check_bai)
    ImageView zhwjCheckBai;
    @BindView(R.id.zhwj_ll_bai)
    LinearLayout zhwjLlBai;
    @BindView(R.id.zhwj_check_cheng)
    ImageView zhwjCheckCheng;
    @BindView(R.id.zhwj_ll_cheng)
    LinearLayout zhwjLlCheng;
    @BindView(R.id.kk_tv_kdsm)
    TextView kkTvKdsm;
    @BindView(R.id.cl_tc_kdsm)
    ConstraintLayout clTcKdsm;
    @BindView(R.id.cl_qianming)
    ConstraintLayout clQianming;
    @BindView(R.id.tv_ltxy)
    TextView tvLtxy;

    private List<View> viewList;
    private List<ZhwjViewHolder> zhwjViewHolderList;
    private int mark = 0; // 标记位
    private int currentCount = 0; // 当前点击的位置
    private HashMap<Integer, String> simMaps = new HashMap<>();
    private HashMap<Integer, Boolean> writeSucMaps = new HashMap<>(); // 标记写卡成功数量
    private int simFlag = 0; // 存储sim卡号的标记位
    private HashMap<Integer, String> numMaps = new HashMap<>();
    private int numFlag = 0; // 存储开户号码的标记位
    private int countFlag = 1; // 每次添加和删除都会增减标记位,以供于清空布局后的再次添加
    private boolean isKdtc = false;
    private int isBaiKa = 1; // 标记选择了白卡还是成卡
    private MyUsualyDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhi_hui_wo_jia);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    protected void initView() {
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.VISIBLE);
        tvName.setText("智慧沃家");
        clTcKdsm.setVisibility(View.GONE);
        dialog = new MyUsualyDialog(ZhiHuiWoJiaActivity.this,
                R.layout.wait_item);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);

        initData();
    }

    @Override
    protected void initData() {
        kuandaiTvAddress.setText(kuandaiAddress);
        kuandaiBuchong.setText(kuandaiAddress);
        kuandaiBuchong.setSelection(kuandaiAddress.length());
        simMaps = new HashMap<>();
        numMaps = new HashMap<>();
        viewList = new ArrayList<>(); // 初始化集合
        zhwjViewHolderList = new ArrayList<>(); // 初始化集合

        addItem(1, simMaps, numMaps); // 第一次加载布局的时候先初始化一条
    }

    @Override
    protected void receiveEvent(Event event) {
        switch (event.getCode()) {
            case EventCodes.EventFaceCode.A: // 实名认证
                phot_lists = PrefUtils.getInt("PHOT_LISTS", 0); // 用户上传的照片(正,反,手持,公安)
                FaceRzInfo data3 = (FaceRzInfo) event.getData();
                if (data3 != null) {
                    face_image = data3.getFace_image();
                    face_ok = data3.getFace_ok();
                    sfz_card = data3.getSfz_card();
                    sfz_name = data3.getSfz_name();
                    sfzPhoto = data3.getSfzPhoto();

                    clSmrzItem.setVisibility(View.VISIBLE);

                    if ("1".equals(face_ok)) {
                        kkTvSmrz.setText("已认证");
                        bluetoothName = PrefUtils.getString("BluetoothName", "");
                    } else if ("2".equals(face_ok)) {
                        kkTvSmrz.setText("待审核");
                        bluetoothName = PrefUtils.getString("BluetoothName", "");
                    } else {
                        kkTvSmrz.setText("请扫描进行认证");
                    }

                    kkTvSmrz.setTextColor(Color.BLACK);
                    kkTvName.setText(sfz_name);
                    kkTvCardnum.setText(sfz_card);
                    // 加载身份证照片
                    Glide.with(ZhiHuiWoJiaActivity.this).load(sfzPhoto).into(kkIvPhoto);
                }
                break;

            case EventCodes.EventReadCardCode.B: // 宽带返回iccid

                ReadIccidAndWriteCardInfo data = (ReadIccidAndWriteCardInfo) event.getData();
                Log.e("项目异常写卡", event.getCode() + "------ReadIccidAndWriteCardInfo--返回iccid----" + data.toString());
                String iccidNum = data.getIccidNum();

                String phoneNumSub = numMaps.get(currentCount);
                Log.e("项目异常写卡", "------phoneNumSub------" + phoneNumSub);
                WriteCardUtils.getKuanDaiImsi(ZhiHuiWoJiaActivity.this, iccidNum, phoneNumSub, sfz_card);
                break;

            case EventCodes.EventReadCardCode.D: // 宽带返回写卡结果

                ReadIccidAndWriteCardInfo xiekaData = (ReadIccidAndWriteCardInfo) event.getData();
                Log.e("项目异常写卡", event.getCode() + "------ReadIccidAndWriteCardInfo-返回写卡结果-----" + xiekaData.toString());
                String errMsg1 = xiekaData.getErrMsg(); // 错误信息
                // 判断errMsg是不是空,是空值就是写卡成功
                if (TextUtils.isEmpty(errMsg1)) {
                    String phoneNumSub1 = numMaps.get(currentCount);
                    Log.e("项目异常写卡", "------phoneNumSub1111------" + phoneNumSub1);

                    boolean isWriteSuc = WriteCardUtils.subKuanDaiWrite(ZhiHuiWoJiaActivity.this);
                    if (isWriteSuc) {
                        writeSucMaps.put(currentCount, true);
                    } else {
                        writeSucMaps.put(currentCount, false);
                    }
                } else {
                    // 写卡失败,提示错误
                    WriteCardUtils.showMsg(ZhiHuiWoJiaActivity.this, "写卡结果", errMsg1);
                    Event<String> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.E);
                    EventBusUtil.sendEvent(clearCardEvent);
                }
                break;
        }
    }

    /**
     * 验证SIM卡
     */
    private void yanZhengSimNum(String simValue) {
        dialog.show();
        MyApplication.getInstance().getHttpTools().getSimNum(isBaiKa + "", "","", simValue,
                "", new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            parseJson(response.body(), simValue);
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "数据解析异常");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "网络或服务器错误");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                    }
                });
    }

    /**
     * 解析数据
     *
     * @param json
     */
    private void parseJson(String json, String simValue) {
        Log.e("项目异常智慧沃家", "------parseSimNumJson------" + json);
        Gson gson = new Gson();
        SimNumInfo simNumInfo = gson.fromJson(json, SimNumInfo.class);
        if (simNumInfo != null) {
            int code = simNumInfo.getCode();
            if (code == 300) {
                List<SimNumInfo.IccidListBean> iccidList = simNumInfo.getIccid_list(); // SIM卡数据
                if (iccidList != null && iccidList.size() > 0) {
                    // 验证成功,添加SIM卡号
                    simMaps.put(currentCount, simValue); // 从零开始添加,方便循环读取

                    Log.e("项目异常智慧沃家", simFlag + "------SIMREQUEST_CODE------" + simValue);
                    for (int i = 0; i < zhwjParent.getChildCount(); i++) {
                        ZhwjViewHolder currentZhwjViewHolder = zhwjViewHolderList.get(i);

                        if (currentCount == currentZhwjViewHolder.id) {
                            setValue(simValue, currentZhwjViewHolder.tvSimNum, currentZhwjViewHolder.id);
                        }
                    }
                } else {
                    ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "未检测到可用SIM卡");
                }
            } else {
                ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this,
                        simNumInfo.getMsg());
            }
        } else {
            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "未获取到数据");
        }
    }

    @OnClick({R.id.zhwj_ll_bai, R.id.zhwj_ll_cheng, R.id.zhwj_add_phone, R.id.cl_select_tc,
            R.id.cl_shiming, R.id.cl_qianming, R.id.tv_ltxy, R.id.dkd_tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.zhwj_ll_bai: // 点击选择白卡改变状态
                isBaiKa = 1;
                clearItem();
                zhwjCheckBai.setImageResource(R.mipmap.kd_xz);
                zhwjCheckCheng.setImageResource(R.mipmap.kd_wxz);
                break;
            case R.id.zhwj_ll_cheng: // 点击选择成卡改变状态
                isBaiKa = 2;
                clearItem();
                zhwjCheckBai.setImageResource(R.mipmap.kd_wxz);
                zhwjCheckCheng.setImageResource(R.mipmap.kd_xz);
                break;
            case R.id.zhwj_add_phone: // 添加号码
                if (simMaps.size() == countFlag) {
                    if (numMaps.size() == countFlag) {
                        if (countFlag < 5) {
                            zhwjAddPhone.setEnabled(false);
                            addItem(1, simMaps, numMaps);
                            countFlag++;
                            zhwjAddPhone.setEnabled(true);
                            if (countFlag == 5) {
                                zhwjAddPhone.setVisibility(View.GONE); // 在号码达到五个之后将添加按钮隐藏掉
                            }
                        } else {
                            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "最多只能选五个号码");
                        }
                    } else {
                        ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "请先选择开户号码" + countFlag);
                    }
                } else {
                    ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "请先选择SIM卡号" + countFlag);
                }
                break;
            case R.id.cl_select_tc: // 选择套餐
                startActivityForResult(new Intent(ZhiHuiWoJiaActivity.this, KuanDaiTaoCanActivity.class)
                        .putExtra("KDTYPE", kdtype), 120);
                break;
            case R.id.cl_shiming: //实名认证
                // 先判断是否选择套餐
                if (isKdtc) {
                    if (simMaps.size() == countFlag && numMaps.size() == countFlag) {
                        startActivity(new Intent(ZhiHuiWoJiaActivity.this, ShiMingRengZhengActivity.class)
                                .putExtra("ISKUANDAI", true).putExtra("SPECID", taocanSpecId));
                    } else {
                        ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "请先完善号码信息");
                    }
                } else {
                    ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "请先选择套餐");
                }
                break;
            case R.id.cl_qianming: // 签名
                startActivityForResult(new Intent(ZhiHuiWoJiaActivity.this, QianMingActivity.class), 0);
                break;
            case R.id.tv_ltxy: // 联通协议
                // 联通协议
                startActivity(new Intent(ZhiHuiWoJiaActivity.this,
                        LianTongXieYiListActivity.class));
                break;
            case R.id.dkd_tv_submit: //提交
                dkdTvSubmit.setEnabled(false);
                if (isSubOrder()) {
                    // 显示键盘
                    ZhiHuiWoJiaActivityPermissionsDispatcher.openCameraWithCheck(this);
                } else {
                    dkdTvSubmit.setEnabled(true);
                }
                break;
        }
    }

    /**
     * 清空所有条目(选择白卡或成卡的时候使用)
     */
    private void clearItem() {
        simMaps.clear();
        numMaps.clear();
        viewList.clear();
        writeSucMaps.clear();
        zhwjViewHolderList.clear();

        zhwjParent.removeAllViews(); // 清空所有布局重新添加

        numFlag = 0;
        simFlag = 0;
        currentCount = 0;
        mark = 0;
        countFlag = 0; // 清空是把所有的条目都清空了,所以本来默认是1的countFlag要归零
        addItem(1, simMaps, numMaps);
        countFlag++;
    }

    /**
     * 判断是否可以提交
     *
     * @return
     */
    private boolean isSubOrder() {
        boolean isSubMit = false;

        if (!isKdtc) {
            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this,
                    "请先选择宽带套餐");
            return isSubMit;
        }
        if (numMaps.size() == 0) {
            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this,
                    "请先选择号码");
            return isSubMit;
        }

        if (numMaps.size() == simMaps.size()) {
            kdPhoneNum = "";
            kdSimNum = "";
            // 说明号码都选完了
            for (int i = 0; i < numMaps.size(); i++) {
                if (i == 0) {
                    kdPhoneNum = numMaps.get(i);
                    kdSimNum = simMaps.get(i);
                } else {
                    kdPhoneNum = kdPhoneNum + "," + numMaps.get(i);
                    kdSimNum = kdSimNum + "," + simMaps.get(i);
                }
            }
            Log.e("项目异常号码", "---kdPhoneNum---" + kdPhoneNum);
            Log.e("项目异常号码", "---kdSimNum---" + kdSimNum);

        } else {
            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this,
                    "请先选择号码");
            return isSubMit;
        }

        if (isBaiKa == 1 && writeSucMaps.size() == 0) {
            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this,
                    "请先进行写卡");
            return isSubMit;
        }
        if (isBaiKa == 1) {
            if (writeSucMaps.size() != numMaps.size()) {
                ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this,
                        "请将所有号码都进行写卡");
                return isSubMit;
            }
        }

        llTvLxhmSub = llTvLxhm.getText().toString().trim();
        payamount = kuandaiZyhf.getText().toString().trim();
        if (!TextUtils.isEmpty(face_image) && face_image != null) {
            if (!TextUtils.isEmpty(llTvLxhmSub)) {
                boolean matches = TextUtils.isDigitsOnly(llTvLxhmSub);
                Log.e("项目异常matches", llTvLxhmSub.length() + "------matches------" + matches);
                if (matches && llTvLxhmSub.length() == 11) {
                    if ("1".equals(sFlag)) {
                        // 先判断权限
                        // showContacts();
                        if (cbXieyi.isChecked()) {
                            isSubMit = true;
                        } else {
                            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this,
                                    "请阅读开卡相关协议并同意");
                        }
                    } else {
                        ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this,
                                "请先签名");
                    }
                } else {
                    ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this,
                            "联系电话格式有误");
                }

            } else {
                ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this,
                        "请输入联系电话");
            }
        } else {
            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this,
                    "请先实名认证");
        }
        return isSubMit;
    }

    /**
     * 动态添加布局
     *
     * @param itemSize 要添加的个数
     * @param simMaps  要添加的sim集合
     * @param numMaps  要添加的phone集合
     */
    private void addItem(int itemSize, HashMap<Integer, String> simMaps, HashMap<Integer, String> numMaps) {
        Log.e("项目异常智慧沃家", "------addItem------" + itemSize);
        for (int i = 0; i < itemSize; i++) {
            View addView = LayoutInflater.from(ZhiHuiWoJiaActivity.this).inflate(R.layout.layout_zhwj_two_view, null);

            ZhwjViewHolder holder = new ZhwjViewHolder();

            holder.id = mark; // 设置标记
            holder.tvSimName = addView.findViewById(R.id.zhwj_sim_num);
            holder.tvSimNum = addView.findViewById(R.id.zhwj_tv_sim_num);

            holder.tvPhoneName = addView.findViewById(R.id.zhwj_kh_phone);
            holder.tvPhoneNum = addView.findViewById(R.id.zhwj_tv_kh_phone);
            holder.ivSys = addView.findViewById(R.id.zhwj_sys);
            holder.ivDelete = addView.findViewById(R.id.zhwj_delete);
            holder.ivWriteCard = addView.findViewById(R.id.zhwj_write_card);

            if (isBaiKa == 1) {
                // 白卡才显示写卡按钮
                holder.ivWriteCard.setVisibility(View.VISIBLE);
            } else {
                holder.ivWriteCard.setVisibility(View.GONE);
            }

            holder.tvSimNum.setTag(mark);
            holder.tvPhoneNum.setTag(mark);

            holder.ivSys.setTag(mark);
            holder.ivDelete.setTag(mark);
            holder.ivWriteCard.setTag(mark);

            holder.tvSimName.setText("SIM卡" + (mark + 1));
            holder.tvPhoneName.setText("开户号" + (mark + 1));

            if (simMaps != null && simMaps.size() > 0) {
                for (int j = 0; j < simMaps.size(); j++) {
                    int tvSimNumTag = (int) holder.tvSimNum.getTag();
                    if (tvSimNumTag == j) {
                        holder.tvSimNum.setText(simMaps.get(j));  // 设置sim卡号
                    }
                }
            }

            if (numMaps != null && numMaps.size() > 0) {
                for (int j = 0; j < numMaps.size(); j++) {
                    int tvPhoneNumTag = (int) holder.tvPhoneNum.getTag();
                    if (tvPhoneNumTag == j) {
                        holder.tvPhoneNum.setText(numMaps.get(j)); // 设置开户号
                    }
                }
            }


            if (mark == 0) {
                // 如果不是最后一个条目就隐藏删除按钮
                holder.ivDelete.setVisibility(View.GONE);
            } else {
                // 如果是集合的最后一个那就显示删除按钮
                holder.ivDelete.setVisibility(View.VISIBLE);
            }

            // 设置监听
            setClick(holder);

            addView.setTag(mark);
            zhwjParent.addView(addView);
            zhwjViewHolderList.add(holder); // 添加holder到集合
            viewList.add(addView); // 添加addView到集合

            mark++; // 标记位加1
            Log.e("项目异常智慧沃家", zhwjViewHolderList.size() + "------zhwjViewHolderList.size()------" + mark);
        }
    }

    /**
     * 设置监听
     *
     * @param holder
     */
    private void setClick(ZhwjViewHolder holder) {
        holder.tvSimNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 选择SIM卡号
                currentCount = (int) v.getTag();
                startActivityForResult(new Intent(ZhiHuiWoJiaActivity.this, KuanDaiSimNumActivity.class)
                        .putExtra("isBaiKa", isBaiKa + ""), SIMREQUEST_CODE);
            }
        });
        holder.tvPhoneNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("项目异常智慧沃家", "------1------" + zhwjParent.getChildCount());
                // 选择号码
                for (int i = 0; i < zhwjParent.getChildCount(); i++) {
                    ZhwjViewHolder currentZhwjViewHolder = zhwjViewHolderList.get(i);
                    Log.e("项目异常智慧沃家", v.getTag() + "------zhwjViewHolderList------" + currentZhwjViewHolder.id);
                    currentCount = (int) v.getTag();
                    if (currentCount == currentZhwjViewHolder.id) {
                        String simNum = currentZhwjViewHolder.tvSimNum.getText().toString().trim();
                        Log.e("项目异常智慧沃家", "------选择号码------" + simNum);
                        startActivityForResult(new Intent(ZhiHuiWoJiaActivity.this, SelectKuanDaiNumActivity.class)
                                .putExtra("ICCIDNO", simNum).putExtra("KDTYPE", kdtype), PHONEREQUEST_CODE);
                    }
                }
            }
        });
        holder.ivSys.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 扫一扫
                currentCount = (int) v.getTag();
                startActivityForResult(new Intent(ZhiHuiWoJiaActivity.this, TiaoXingCodeScanerActivity.class), CODEREQUEST_CODE);
            }
        });

        holder.ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentCount = (int) v.getTag();
                // 删除item
                deleteItem();
            }
        });
        holder.ivWriteCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 写卡
                currentCount = (int) v.getTag();
                String phoneNumSub = numMaps.get(currentCount);
                Log.e("项目异常写卡", "------phoneNumSub0000------" + phoneNumSub);
                if (!TextUtils.isEmpty(sfz_card)) {
                    startActivity(new Intent(ZhiHuiWoJiaActivity.this, WriteCardActivity.class)
                            .putExtra("WriteType", 1));
                } else {
                    ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "请先实名认证再进行写卡");
                }
            }
        });
    }

    /**
     * 赋值
     *
     * @param value
     * @param tvitem
     * @param id
     */
    private void setValue(String value, TextView tvitem, int id) {
        Log.e("项目异常智慧沃家", value + "------setValue------" + id);
        tvitem.setTag(id);
        tvitem.setText(value);
    }

    /**
     * 删除item
     */
    private void deleteItem() {
        zhwjAddPhone.setVisibility(View.VISIBLE); // 在删除的时候将添加按钮显示出来
        Log.e("项目异常智慧沃家deleteItem", simFlag + "=====Flag====" + numFlag);

        int childNum = zhwjParent.getChildCount();
        Log.e("项目异常智慧沃家deleteItem", "一共有" + childNum + "个布局" + "--删除的是第" + currentCount + "个标记位,集合的大小是:==" + simMaps.size());
        for (int i = 0; i < childNum; i++) {

            if (i >= currentCount) {
                // 循环的时候判断下,如果循环到大于等于点击的当前布局,那么就要注意重新赋值了
                // 删除前把所有的值重新排序
                Log.e("项目异常智慧沃家deleteItem", i + "获取集合的值为:=" + simMaps.get(i));
                // 如果点击的不是最后一个布局,那么就将下一个布局的值整体前移一位到点击布局的key(这么做是为了在删除布局的时候不影响显示顺序)
                if (i == (childNum - 1)) {
                    // 如果循环到最后一个布局,那么直接将该值删除就行
                    simMaps.remove(i);
                    numMaps.remove(i);
                    Log.e("项目异常智慧沃家deleteItem", i + "--删除的是最后一条-----循环到最后一个布局之后集合的大小是:===" + simMaps.size());
                } else {
                    Log.e("项目异常智慧沃家deleteItem", i + "----重新赋值----" + simMaps.get(i + 1));
                    simMaps.put(i, simMaps.get(i + 1));  // 点击2的时候给2添加3的值
                    numMaps.put(i, numMaps.get(i + 1)); // 循环到3的时候给3添加4的值
                }
            }
            zhwjParent.removeAllViews(); // 清空所有布局重新添加
            zhwjViewHolderList.clear(); // 清空所有holder集合
            viewList.clear(); // 清空所有重复布局集合
        }
        mark = 0; // 标记位归零
        countFlag--; // 布局删除完之后标记位减一
        addItem(countFlag, simMaps, numMaps); // 每次删除之后重新遍历添加布局
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SIMREQUEST_CODE: // 获取SIM卡号返回
                    String sim_num = data.getStringExtra("SIM_NUM");


                    for (int i = 0; i < currentCount; i++) {

                        if (simMaps.get(i).equals(sim_num)) {
                            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "此SIM号已选择");
                            return;
                        }
                    }


                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            yanZhengSimNum(sim_num); // 验证SIM卡

                        }
                    }, 200);

                    break;
                case PHONEREQUEST_CODE: // 获取开户号码返回
                    String phone_num = data.getStringExtra("PHONE_NUM");

                    for (int i = 0; i < currentCount; i++) {

                        if (numMaps.get(i).equals(phone_num)) {
                            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "此开户号已选择");
                            return;
                        }
                    }

                    numMaps.put(currentCount, phone_num); // 从零开始添加,方便循环读取

                    Log.e("项目异常智慧沃家", numFlag + "------PHONEREQUEST_CODE------" + phone_num);
                    for (int i = 0; i < zhwjParent.getChildCount(); i++) {
                        ZhwjViewHolder currentZhwjViewHolder = zhwjViewHolderList.get(i);

                        if (currentCount == currentZhwjViewHolder.id) {
                            setValue(phone_num, currentZhwjViewHolder.tvPhoneNum, currentZhwjViewHolder.id);
                        }
                    }
                    break;
                case 120:
                    // 选套餐返回
                    isKdtc = true;
                    String taocanName = data.getStringExtra("TAOCAN_NAME");
                    String taocanSulv = data.getStringExtra("TAOCAN_SULV");
                    taocanSpecId = data.getStringExtra("TAOCAN_SPEC_ID");
                    clTcKdsm.setVisibility(View.VISIBLE);
                    kkTvKdsm.setText(taocanSulv);
                    kkTvXzhm.setText(taocanName);
                    break;
            }
        } else if (resultCode == 0) {
            // 二维码返回
            if (requestCode == CODEREQUEST_CODE) {
                if (data != null) {
                    Bundle str = data.getExtras();
                    if (str != null) {
                        String result = str.getString(CodeUtils.RESULT_STRING);
                        int resultType = str.getInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
                        Log.e("项目异常智慧沃家", resultType + "------CODEREQUEST_CODE------" + result);
                        switch (resultType) {
                            case CodeUtils.RESULT_SUCCESS:
                                if (result != null) {
                                    if (result.length() >= 19) {
                                        String keyvalue = result.substring(0, 19);
                                        if (TextUtil.isNumeric(keyvalue)) {
                                            // 是纯数字
                                            for (int i = 0; i < currentCount; i++) {
                                                if (simMaps.get(i).equals(keyvalue)) {
                                                    ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "此SIM号已选择");
                                                    return;
                                                }
                                            }

                                            yanZhengSimNum(keyvalue); // 验证SIM卡
                                        } else {
                                            ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "请确定您扫描的是SIM卡1");
                                        }
                                    } else {
                                        ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "请确定您扫描的是SIM卡2");
                                    }
                                } else {
                                    ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "扫描失败，请重新扫描1");
                                }
                                break;
                            case CodeUtils.RESULT_FAILED:
                                ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "扫描失败，请重新扫描2");
                                break;
                        }
                    }
                } else {
                    ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "扫描失败，请重新扫描3");
                }
            }
        } else if (resultCode == 2) {
            if (data != null) {
                // 签名url
                String sName = data.getStringExtra("fileName");
                // 是否签名
                sFlag = data.getStringExtra("signFlag");
                // 签名带回的金额
                sMoney = data.getStringExtra("signMoney");

                Log.e("项目异常", "----getStringExtra--sMoney------" + sMoney);
                Log.e("项目异常", "----getStringExtra--sName------" + sName);
                if (!TextUtils.isEmpty(sName)) {
                    // 加载签名照片
                    ImageLoader.getInstance()
                            .displayImage(sName, kkQianmingPhoto, new DisplayImageOptions.Builder()
                                    .cacheInMemory(true)//默认会在内存缓存
                                    .cacheOnDisk(true)//默认会在硬盘缓存
                                    .displayer(new FadeInBitmapDisplayer(1000)).build());
                }
            } else {
                ToastUtils.showShortToast(ZhiHuiWoJiaActivity.this, "未获取到签名");
            }
        }
    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void openCamera() {
        // 获取手机信息
        Log.e("项目异常", "openCamera权限: =================");
        dkdTvSubmit.setEnabled(true);
        getLocationPrem();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ZhiHuiWoJiaActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void showCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获手机定位权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void denied() {
        Log.e("权限", "------denied------");
        //        loginBtnLogin.setEnabled(true);
        // 获取手机信息
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                getLocationPrem();
            }
        });
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void askAgain() {
        Log.e("权限", "------askAgain------");
        //        loginBtnLogin.setEnabled(true);
        // 获取手机信息
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                getLocationPrem();
            }
        });
    }
}
